import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // 设置页面的标题
  document.title = getPageTitle(to.meta.title)
  // 获取token
  const hasToken = getToken()

  // 判断是否存在token
  if (hasToken) {
    // 是否是从登录来的请求
    if (to.path === '/login') {
      // 跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 从store里面获取用户信息
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next() // 放行
      } else {
        try {
          // 如果用户信息不存在，就会从服务器获取用户信息
          const { roles } = await store.dispatch('user/getInfo')
          // 从服务器获取菜单、路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          const obj = { path: '*', redirect: '/404', hidden: true }
          accessRoutes.push(obj)
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
